import argparse
import os

import pytest

from config.path_config import path_config
from utils.logger import logger


def run_pytest(env='xxxx-test3', deploy='local', key='all', mark='all', pyargs='all'):
    os.environ['env'] = env
    os.environ['deploy'] = deploy
    os.environ['key'] = key
    os.environ['mark'] = mark
    os.environ['pyargs'] = pyargs
    allure_result = path_config.allure_result_dir
    pytest_args = []
    if pyargs != "all" or pyargs is None:
        runTestPath = "%s/%s" % (path_config.testcase_dir, pyargs)

    else:
        runTestPath = path_config.testcase_dir
    pytest_args.append(f"{runTestPath}")
    logger.info(f"执行{runTestPath}目录下的用例")

    pytest_args.extend([
        "-v", "-s",
        f'--alluredir={allure_result}', "--clean-alluredir",
        "--reruns=0", "-n", "2"])

    # "-n", "auto", "--dist=loadfile",
    if mark != "all" or mark is None:
        pytest_args.append(f"-m={mark}")
        logger.info(f"执行标记为{mark}的用例")
        logger.info(pytest_args)
    else:
        if key != "all" or key is None:
            pytest_args.append(f"-k={key}")
            logger.info(f"执行含关键字{key}的用例")
            logger.info(pytest_args)
        elif pyargs == 'all':
            logger.info("执行全部用例")

    pytest.main(pytest_args)


def parse_args():
    parser = argparse.ArgumentParser(description='运行测试用例并生成 Allure 报告')
    parser.add_argument('--env', type=str,
                      choices=['xxxx-test', 'xxxx-test2', 'xxxx-test3', 'xxxx'],
                      help='运行环境选择', default='xxxx-test3')
    parser.add_argument('--deploy', type=str,
                      choices=['local', 'k8s'], help='部署环境类型', default='local')
    parser.add_argument('--key', help='指定测试关键字', default='all')
    parser.add_argument('--mark', help='指定测试标记执行，优先于key', default='all')
    parser.add_argument('--pyargs', help='指定目录下执行，可与key和mark结合', default='all')
    return parser.parse_args()


def generate_allure_report():
    "生成allure报告"
    allure_report = path_config.allure_report_dir
    allure_result = path_config.allure_result_dir
    allure_cmd = "allure"
    os.system(f'{allure_cmd} generate {allure_result} -o {allure_report} --clean')


if __name__ == '__main__':
    args = parse_args()
    run_pytest(env=args.env, deploy=args.deploy, key=args.key, mark=args.mark, pyargs=args.pyargs)